"""
增强分析模块
包含更多深度分析功能
"""

import pandas as pd
import numpy as np
from typing import Dict, List, Tuple


class EnhancedAnalyzer:
    """增强分析类 - 提供更多维度的分析"""
    
    @staticmethod
    def analyze_volume_price_relation(df: pd.DataFrame) -> Dict:
        """
        量价关系分析
        """
        if len(df) < 5:
            return {}
        
        latest = df.iloc[-5:]  # 最近5天
        
        analysis = {}
        
        # 量价齐升
        price_up = (latest['收盘'].diff() > 0).sum()
        volume_up = (latest['成交量'].diff() > 0).sum()
        
        if price_up >= 4 and volume_up >= 4:
            analysis['量价关系'] = "量价齐升"
            analysis['评价'] = "✅ 健康的上涨趋势"
            analysis['建议'] = "可继续持有或加仓"
        elif price_up >= 4 and volume_up <= 2:
            analysis['量价关系'] = "价涨量缩"
            analysis['评价'] = "⚠️ 上涨动能不足"
            analysis['建议'] = "谨慎，可能面临调整"
        elif price_up <= 2 and volume_up >= 4:
            analysis['量价关系'] = "价跌量增"
            analysis['评价'] = "⚠️ 抛压较大"
            analysis['建议'] = "观望或减仓"
        else:
            analysis['量价关系'] = "震荡整理"
            analysis['评价'] = "📊 横盘整理中"
            analysis['建议'] = "等待方向明确"
        
        return analysis
    
    @staticmethod
    def analyze_chip_distribution(df: pd.DataFrame) -> Dict:
        """
        简化版筹码分布分析
        """
        if len(df) < 20:
            return {}
        
        recent_20 = df.tail(20)
        current_price = df.iloc[-1]['收盘']
        
        # 计算近20日的价格分布
        price_counts = pd.cut(recent_20['收盘'], bins=10).value_counts()
        
        # 找出筹码集中区域
        max_bin = price_counts.idxmax()
        chip_center = (max_bin.left + max_bin.right) / 2
        
        # 计算当前价格相对筹码集中区的位置
        position = (current_price - chip_center) / chip_center * 100
        
        analysis = {
            '筹码集中价位': f"¥{chip_center:.2f}",
            '当前价格': f"¥{current_price:.2f}",
            '相对位置': f"{position:+.2f}%"
        }
        
        if position > 10:
            analysis['状态'] = "高位运行"
            analysis['提示'] = "⚠️ 价格明显高于筹码集中区"
        elif position < -10:
            analysis['状态'] = "低位运行"
            analysis['提示'] = "💎 价格明显低于筹码集中区"
        else:
            analysis['状态'] = "筹码区域内"
            analysis['提示'] = "📊 价格在筹码集中区域"
        
        return analysis
    
    @staticmethod
    def analyze_trend_strength(df: pd.DataFrame) -> Dict:
        """
        趋势强度分析
        """
        if len(df) < 20:
            return {}
        
        analysis = {}
        
        # ADX趋势强度
        if 'ADX' in df.columns:
            latest_adx = df.iloc[-1]['ADX']
            
            if pd.notna(latest_adx):
                analysis['ADX值'] = f"{latest_adx:.2f}"
                
                if latest_adx > 40:
                    analysis['趋势强度'] = "极强趋势"
                    analysis['ADX评价'] = "🔥 趋势非常明显"
                elif latest_adx > 25:
                    analysis['趋势强度'] = "强趋势"
                    analysis['ADX评价'] = "✅ 趋势较为明显"
                elif latest_adx > 20:
                    analysis['趋势强度'] = "中等趋势"
                    analysis['ADX评价'] = "📊 有一定趋势"
                else:
                    analysis['趋势强度'] = "无趋势"
                    analysis['ADX评价'] = "⚠️ 震荡行情"
        
        # 方向判断（DMI）
        if 'PDI' in df.columns and 'MDI' in df.columns:
            latest_pdi = df.iloc[-1]['PDI']
            latest_mdi = df.iloc[-1]['MDI']
            
            if pd.notna(latest_pdi) and pd.notna(latest_mdi):
                if latest_pdi > latest_mdi:
                    analysis['趋势方向'] = "上升趋势"
                    analysis['DMI信号'] = f"✅ +DI({latest_pdi:.2f}) > -DI({latest_mdi:.2f})"
                else:
                    analysis['趋势方向'] = "下降趋势"
                    analysis['DMI信号'] = f"⚠️ +DI({latest_pdi:.2f}) < -DI({latest_mdi:.2f})"
        
        return analysis
    
    @staticmethod
    def analyze_momentum(df: pd.DataFrame) -> Dict:
        """
        动量分析
        """
        if len(df) < 20:
            return {}
        
        analysis = {}
        latest = df.iloc[-1]
        
        # ROC 变动率
        if 'ROC' in df.columns and pd.notna(latest['ROC']):
            analysis['ROC'] = f"{latest['ROC']:.2f}%"
            
            if latest['ROC'] > 5:
                analysis['ROC评价'] = "🚀 上涨动能强劲"
            elif latest['ROC'] > 0:
                analysis['ROC评价'] = "✅ 上涨动能温和"
            elif latest['ROC'] > -5:
                analysis['ROC评价'] = "⚠️ 下跌动能温和"
            else:
                analysis['ROC评价'] = "❌ 下跌动能强劲"
        
        # CCI 顺势指标
        if 'CCI' in df.columns and pd.notna(latest['CCI']):
            analysis['CCI'] = f"{latest['CCI']:.2f}"
            
            if latest['CCI'] > 100:
                analysis['CCI评价'] = "⚠️ 超买，可能回调"
            elif latest['CCI'] < -100:
                analysis['CCI评价'] = "💎 超卖，可能反弹"
            else:
                analysis['CCI评价'] = "📊 正常区间"
        
        # 威廉指标
        if 'WR14' in df.columns and pd.notna(latest['WR14']):
            analysis['WR'] = f"{latest['WR14']:.2f}"
            
            if latest['WR14'] > -20:
                analysis['WR评价'] = "⚠️ 超买区域"
            elif latest['WR14'] < -80:
                analysis['WR评价'] = "💎 超卖区域"
            else:
                analysis['WR评价'] = "📊 正常区间"
        
        return analysis
    
    @staticmethod
    def analyze_support_resistance(df: pd.DataFrame) -> Dict:
        """
        支撑位和压力位分析
        """
        if len(df) < 20:
            return {}
        
        recent_data = df.tail(60) if len(df) >= 60 else df
        current_price = df.iloc[-1]['收盘']
        
        # 使用最高价和最低价的分位数计算支撑压力位
        highs = recent_data['最高']
        lows = recent_data['最低']
        
        resistance_levels = [
            highs.quantile(0.90),
            highs.quantile(0.75),
            highs.max()
        ]
        
        support_levels = [
            lows.quantile(0.10),
            lows.quantile(0.25),
            lows.min()
        ]
        
        # 找出最近的支撑和压力
        resistance_above = [r for r in resistance_levels if r > current_price]
        support_below = [s for s in support_levels if s < current_price]
        
        analysis = {}
        
        if resistance_above:
            nearest_resistance = min(resistance_above)
            analysis['最近压力位'] = f"¥{nearest_resistance:.2f}"
            analysis['压力距离'] = f"{(nearest_resistance - current_price) / current_price * 100:.2f}%"
        
        if support_below:
            nearest_support = max(support_below)
            analysis['最近支撑位'] = f"¥{nearest_support:.2f}"
            analysis['支撑距离'] = f"{(current_price - nearest_support) / current_price * 100:.2f}%"
        
        return analysis
    
    @staticmethod
    def calculate_comprehensive_score(df: pd.DataFrame, realtime_data: Dict = None) -> Tuple[float, List[str]]:
        """
        综合评分（基于更多指标）
        """
        if len(df) < 20:
            return 50.0, ["数据不足，无法全面评估"]
        
        score = 50  # 基准分
        signals = []
        
        latest = df.iloc[-1]
        prev = df.iloc[-2] if len(df) > 1 else latest
        
        # 1. ADX趋势分析（20分）
        if 'ADX' in latest and pd.notna(latest['ADX']):
            if latest['ADX'] > 25:
                if 'PDI' in latest and 'MDI' in latest:
                    if latest['PDI'] > latest['MDI']:
                        score += 20
                        signals.append("✅ 强劲上升趋势（ADX）")
                    else:
                        score -= 15
                        signals.append("⚠️ 强劲下降趋势（ADX）")
        
        # 2. CCI 超买超卖（15分）
        if 'CCI' in latest and pd.notna(latest['CCI']):
            if -100 < latest['CCI'] < 100:
                score += 10
                signals.append("✅ CCI正常区间")
            elif latest['CCI'] < -100:
                score += 15
                signals.append("💎 CCI超卖，可能反弹")
            else:
                score -= 10
                signals.append("⚠️ CCI超买")
        
        # 3. 威廉指标（10分）
        if 'WR14' in latest and pd.notna(latest['WR14']):
            if latest['WR14'] < -80:
                score += 10
                signals.append("💎 WR超卖区域")
            elif latest['WR14'] > -20:
                score -= 10
                signals.append("⚠️ WR超买区域")
        
        # 4. ROC动能（15分）
        if 'ROC' in latest and pd.notna(latest['ROC']):
            if latest['ROC'] > 5:
                score += 15
                signals.append("🚀 ROC显示强劲上涨动能")
            elif latest['ROC'] < -5:
                score -= 15
                signals.append("⚠️ ROC显示下跌动能")
        
        # 5. OBV量能（10分）
        if 'OBV' in df.columns and len(df) > 5:
            obv_trend = df['OBV'].tail(5).diff().mean()
            if obv_trend > 0 and latest['收盘'] > prev['收盘']:
                score += 10
                signals.append("✅ 量价配合良好")
            elif obv_trend < 0 and latest['收盘'] < prev['收盘']:
                score -= 10
        
        # 6. BIAS乖离率（10分）
        if 'BIAS6' in latest and pd.notna(latest['BIAS6']):
            if -3 < latest['BIAS6'] < 3:
                score += 10
                signals.append("✅ 价格接近均线")
            elif latest['BIAS6'] < -10:
                score += 8
                signals.append("💎 价格严重偏离均线（超卖）")
            elif latest['BIAS6'] > 10:
                score -= 8
                signals.append("⚠️ 价格严重偏离均线（超买）")
        
        # 7. PSY心理线（10分）
        if 'PSY' in latest and pd.notna(latest['PSY']):
            if 25 < latest['PSY'] < 75:
                score += 10
            elif latest['PSY'] < 25:
                score += 8
                signals.append("💎 PSY超卖")
            elif latest['PSY'] > 75:
                score -= 8
                signals.append("⚠️ PSY超买")
        
        # 标准化分数
        final_score = max(0, min(100, score))
        
        return final_score, signals

